package org.ysh.core.attachment;

import org.ysh.annotation.AdditionInfoResolver;
import org.apache.poi.hpsf.CustomProperties;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hwpf.HWPFDocument;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;

import static org.ysh.core.attachment.Word2007AdditionInfoResolver.*;


@AdditionInfoResolver(extensions = {"doc"})
public class Word2003AdditionInfoResolver implements AttachmentAdditionInfoResolver {

    @Override
    public void addAdditionInfo(File tmpFile, AdditionInfo additionInfo) throws Exception {
        try(HWPFDocument document = new HWPFDocument(Files.newInputStream(tmpFile.toPath()));
            OutputStream fos = Files.newOutputStream(tmpFile.toPath())){
            PoiHelper.writeCustomInfo(document.getDocumentSummaryInformation(),additionInfo);
            document.write(fos);
        }
    }

    @Override
    public AdditionInfo readAdditionInfo(InputStream in) throws Exception {
        try(HWPFDocument document = new HWPFDocument(in)){
            DocumentSummaryInformation dsi = document.getDocumentSummaryInformation();
            CustomProperties customProperties = dsi.getCustomProperties();
            if(customProperties != null){
                AdditionInfo additionInfo = new AdditionInfo();
                additionInfo.setUserName((String)customProperties.get(CUSTOM_USER));
                additionInfo.setHost((String)customProperties.get(CUSTOM_HOST));
                additionInfo.setTime(new Date(Long.valueOf((String)customProperties.get(CUSTOM_TIME))));
                return additionInfo;
            }
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        String wordPath = "C:\\Users\\hxs_2\\Documents\\关于2021年度省级预算执行和其他财政收支情况的审计结果报告-省政府(1).doc";
        Word2003AdditionInfoResolver word2003AdditionInfo = new Word2003AdditionInfoResolver();
        AdditionInfo additionInfo = new AdditionInfo();
        additionInfo.setUserName("Lisssi");
        additionInfo.setTime(new Date());
        additionInfo.setHost("192.168.1.1");
        word2003AdditionInfo.addAdditionInfo(new File(wordPath),additionInfo);
        additionInfo = word2003AdditionInfo.readAdditionInfo(Files.newInputStream(Paths.get(wordPath)));
        System.out.println(additionInfo);
    }


}
